//
//  XYJLanguageViewController.m
//  徙游记-01
//
//  Created by hcios on 2017/7/17.
//  Copyright © 2017年 鹿林. All rights reserved.
//

#import "XYJLanguageViewController.h"
#import "XYJLanguageTopView.h"
#import "XYJLanguageFromViewController.h"
#import "XYJLanguageToViewController.h"
#import "XYJLanguageTableViewCell.h"
#import "XYJSeeCellTextViewController.h"

#import "NSString+CNToEn.h"
#import "NSString+md5.h"
#import <iflyMSC/iflyMSC.h>

@interface XYJLanguageViewController ()<XYJLanguageTopViewDelegate,UITextFieldDelegate,UICollectionViewDelegate,UICollectionViewDataSource,IFlyRecognizerViewDelegate,XYJLanguageTableViewCellDelegate>{
    
    NSString *languageStringFrom;
    NSString *languageStringTo;
    XYJLanguageTopView *topView;
    UIView *bottomView;
    
    UITextField *textFieldF;
//    UIButton *voiceBtn;
    
    //键盘输入内容
    NSString *inputString;
    
    //取出翻译值和原始值
    NSString *translationString;
    NSString *originString;
    
    //翻译数组
    NSMutableArray *translationArray;
    NSMutableArray *originArray;
    
    //cell高度
    double cellHeight;
    
    //语音
    IFlyRecognizerView *_iflyReconizerView;
    //语音键盘
    UIView *voiceView;
    //语音
    NSString *voiceString;
    
}

@property (nonatomic,strong) UICollectionView *cardView;

@end

static NSString *const CollectionViewCellIdentifier = @"cellID";

@implementation XYJLanguageViewController

-(instancetype)init{
    if (self = [super init]) {
        languageStringFrom = @"自动检测";
        languageStringTo = @"英语";
        translationArray = [[NSMutableArray alloc] init];
        originArray = [[NSMutableArray alloc] init];
    }
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupTopView];
    //初始化语音识别
    [self initIFly];
    [self initAppid];
    //初始化CollectionView
    [self layoutCollectionView];
    [self setupBottomView];

    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"语言翻译";
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeLanguage:) name:@"sender" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeLanguageAgain:) name:@"changeLanguage" object:nil];
    
    
    //增加监听,当键盘出现或者改变时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    
    //增加监听，当键盘退出时接收消息
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];

    
}


#pragma mark - 语音识别初始化
-(void)initIFly{
    //单例模式，无UI的实例化
    if (_iflyReconizerView == nil) {
        _iflyReconizerView = [[IFlyRecognizerView alloc] initWithCenter:self.view.center];
        _iflyReconizerView.delegate = self;
    }
    
    //设置参数
    if (_iflyReconizerView != nil) {
        //扩展参数
        [_iflyReconizerView setParameter:@"" forKey:[IFlySpeechConstant PARAMS]];
        //设置听写模式
        [_iflyReconizerView setParameter:@"iat" forKey:[IFlySpeechConstant IFLY_DOMAIN]];
        //设置最长录音时间
        [_iflyReconizerView setParameter:@"30000" forKey:[IFlySpeechConstant SPEECH_TIMEOUT]];
        //设置后端点
        [_iflyReconizerView setParameter:@"1800" forKey:[IFlySpeechConstant VAD_EOS]];
        //设置前端点
        [_iflyReconizerView setParameter:@"1800" forKey:[IFlySpeechConstant VAD_BOS]];
        //网络等待时间
        [_iflyReconizerView setParameter:@"20000" forKey:[IFlySpeechConstant NET_TIMEOUT]];
        //设置采样率，推荐使用16k
        [_iflyReconizerView setParameter:@"16000" forKey:[IFlySpeechConstant SAMPLE_RATE]];
        //设置语言
        [_iflyReconizerView setParameter:@"zh_cn" forKey:[IFlySpeechConstant LANGUAGE]];
        //设置方言
        [_iflyReconizerView setParameter:@"mandarin" forKey:[IFlySpeechConstant ACCENT]];
        //设置是否返回标点符号
        [_iflyReconizerView setParameter:@"1" forKey:[IFlySpeechConstant ASR_PTT]];
        //设置数据返回格式
        [_iflyReconizerView setParameter:@"plain" forKey:[IFlySpeechConstant RESULT_TYPE]];
    }
}


//语音搜索启动
-(void)voiceStart{
    //启动识别服务
    [_iflyReconizerView start];
}

//结束录音
-(void)voiceEnd{
    //结束识别服务
    [_iflyReconizerView cancel];
}


/*
 识别结果返回代理
 @param resultArray 识别结果
 @param isLast  表示是否最后一次结果
 */
-(void)onResult:(NSArray *)resultArray isLast:(BOOL)isLast{
    [resultArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSLog(@"%@",obj);
        NSArray *array = [obj allKeys];
        voiceString = array[0];
        [self voiceNetWorking];
    }];
}


/*
 识别会话错误返回代理
 @param error 错误码
 */
-(void)onError:(IFlySpeechError *)error{
    NSLog(@"语音识别出错：%@",error);
}

#pragma mark - 初始化Appid
-(void)initAppid{
    //注册讯飞语音
    NSString *initString = [[NSString alloc] initWithFormat:@"appid=%@",@"58f82d69"];
    [IFlySpeechUtility createUtility:initString];
}

#pragma mark - 初始化CollectionView
-(void)layoutCollectionView{
    //初始化layout
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    //滑动方向
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    //设置每个cell的大小
    layout.itemSize = CGSizeMake(SCREEN_WIDTH - 20, 110);
    
    //每个cell之间的距离
    layout.minimumLineSpacing = 10.0f;
    self.cardView = [[UICollectionView alloc] initWithFrame:RECT_MAKE(0, 30, SCREEN_WIDTH, SCREEN_HEIGHT - 94) collectionViewLayout:layout];
    self.cardView.delegate = self;
    self.cardView.dataSource = self;
    self.cardView.showsVerticalScrollIndicator = NO;
    
    //注册cell
    [self.cardView registerClass:[XYJLanguageTableViewCell class] forCellWithReuseIdentifier:@"cellID"];
    self.cardView.backgroundColor = RGB(230, 241, 243);
    [self.view addSubview:self.cardView];
    
}


#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return translationArray.count;
}
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    XYJLanguageTableViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CollectionViewCellIdentifier forIndexPath:indexPath];
    [cell layoutWithTranslationString:translationArray[indexPath.item] originString:originArray[indexPath.item] withIndex:indexPath];
    cell.backgroundColor = [UIColor whiteColor];
    cell.delegate = self;
    return cell;
}


#pragma mark - UICollectionViewDelegate
//设置边距
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(10.0f, 10.0f, 0.0f, 10.0f);
}

//设置Header
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    return CGSizeZero;
}




//销毁通知
-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"changeLanguage" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"sender" object:nil];
}

#pragma mark - XYJLanguageTableViewCellDelegate
-(void)deleteCell:(id)sender{
    UIButton *btn = sender;
    NSLog(@"%ld",(long)btn.tag);
    [translationArray removeObjectAtIndex:btn.tag];
    [originArray removeObjectAtIndex:btn.tag];
    [self.cardView reloadData];
}

-(void)seeCell:(id)sender{
    UIButton *btn = sender;
    NSLog(@"%ld",(long)btn.tag);
    XYJSeeCellTextViewController *VC = [[XYJSeeCellTextViewController alloc] init];
    VC.translationText = translationArray[btn.tag];
    [self presentViewController:VC animated:YES completion:nil];
}


-(void)setupBottomView{
//    bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT - 104, SCREEN_WIDTH, 40)];
//    bottomView.backgroundColor = [UIColor redColor];
//    [self.view addSubview:bottomView];
//    
//    voiceBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//    [voiceBtn setFrame:CGRectMake(5, 5, 30, 30)];
//    voiceBtn.layer.cornerRadius = 15;
//    voiceBtn.layer.masksToBounds = YES;
//    [voiceBtn setBackgroundColor:[UIColor cyanColor]];
//    [voiceBtn addTarget:self action:@selector(clickBtn) forControlEvents:UIControlEventTouchUpInside];
//    [bottomView addSubview:voiceBtn];
//    
//    textFieldF = [[UITextField alloc] initWithFrame:CGRectMake(CGRectGetMaxX(voiceBtn.frame) + 5, 5, bottomView.frame.size.width - 45, 30)];
//    textFieldF.delegate = self;
//    textFieldF.borderStyle = UITextBorderStyleRoundedRect;
//    [bottomView addSubview:textFieldF];
    
    voiceView = [[UIView alloc] initWithFrame:RECT_MAKE(0, SCREEN_HEIGHT - 114, SCREEN_WIDTH, 50)];
    voiceView.backgroundColor = [UIColor whiteColor];
    voiceView.userInteractionEnabled = YES;
    
    //键盘输入
    textFieldF = [[UITextField alloc] initWithFrame:RECT_MAKE(50, 5, SCREEN_WIDTH - 65, 40)];
    textFieldF.placeholder = @"请输入内容";
    textFieldF.layer.cornerRadius = 4;
    textFieldF.layer.masksToBounds = YES;
    textFieldF.delegate = self;
    textFieldF.keyboardType = UIKeyboardTypeDefault;
    textFieldF.font = [UIFont fontWithName:FONT_NAME_LTH size:13];
    textFieldF.borderStyle = UITextBorderStyleRoundedRect;
    //语音切换按钮
    UIButton *voiceBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [voiceBtn setFrame:RECT_MAKE(5, 5, 40, 40)];
    voiceBtn.layer.masksToBounds = YES;
    voiceBtn.layer.cornerRadius = 20;
    [voiceBtn setImage:[UIImage imageNamed:@"voice_record"] forState:UIControlStateNormal];
    [voiceBtn addTarget:self action:@selector(voiceStart) forControlEvents:UIControlEventTouchUpInside];
    
    [voiceView addSubview:voiceBtn];
    [voiceView addSubview:textFieldF];
    [self.view addSubview:voiceView];
}



-(void)textFieldDidBeginEditing:(UITextField *)textField{
    
    textField.text = nil;
    //    _textField.backgroundColor = [UIColor cyanColor];
    [UIView animateWithDuration:0.7 animations:^{
        CGFloat offset = SCREEN_HEIGHT - 398;
        voiceView.frame = RECT_MAKE(0.0f, offset, SCREEN_WIDTH, 50);
    }];
}

//输入框编辑完成以后，将视图恢复到原始状态
-(void)textFieldDidEndEditing:(UITextField *)textField{
    
    [UIView animateWithDuration:0.7 animations:^{
        voiceView.frame = RECT_MAKE(0, SCREEN_HEIGHT - 114, SCREEN_WIDTH, 50);
    }];
    inputString = textField.text;
    [self netWorking];
}


-(void)voiceNetWorking{
    NSLog(@"成功");
    NSString *sign = [NSString stringWithFormat:@"20170114000035852%@1435663218VH_Ufqrfp7f6sBEYkN2B",voiceString];
    NSString *encodedValue = voiceString;
    //去除空格
    NSString *signTo = [sign stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSString *urlString = [NSString stringWithFormat:@"http://api.fanyi.baidu.com/api/trans/vip/translate?q=%@&from=%@&to=%@&appid=20170114000035852&salt=1435663218&sign=%@",[encodedValue stringByReplacingOccurrencesOfString:@" " withString:@""],[NSString fromLan:languageStringFrom],[NSString fromLan:languageStringTo],[NSString md5:signTo]];
    urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [[SeverceHttpRequest sharedManager] GET:urlString parameters:nil success:^(id reponseObject) {
        NSLog(@"%@",reponseObject);
        for (NSDictionary *dict in reponseObject[@"trans_result"]) {
            translationString = dict[@"dst"];
            originString = dict[@"src"];
            //添加数据
            //添加判断(排除位置错误)
            if (![translationString isEqualToString:@"."]) {
                [translationArray addObject:translationString];
                [originArray addObject:originString];
            }
        }
        [self.cardView reloadData];
    } failure:^(NSError *error) {
        NSLog(@"失败");
    }];
    
}


//发送网络请求
-(void)netWorking{
    
    /*
     http://api.fanyi.baidu.com/api/trans/vip/translate
     App ID：20170114000035852
     密钥：VH_Ufqrfp7f6sBEYkN2B
     */
    //转换成UTF-8
    NSString *encodedValue = textFieldF.text;
    
    //判断是否是中文 1435883218
    for (int i = 0; i < [textFieldF.text length]; i++) {
        int a = [textFieldF.text characterAtIndex:i];
        if (a > 0x4e00 && a < 0x9fff) {
            
            encodedValue = [textFieldF.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        }
    }
    
    NSString *fromString = [NSString fromLan:languageStringFrom];
    NSString *toString = [NSString fromLan:languageStringTo];
    NSString *sign = [NSString stringWithFormat:@"20170114000035852%@1435663218VH_Ufqrfp7f6sBEYkN2B",textFieldF.text];
    NSString *signTo = [sign stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSString *urlString = [NSString stringWithFormat:@"https://fanyi-api.baidu.com/api/trans/vip/translate?q=%@&from=%@&to=%@&appid=20170114000035852&salt=1435663218&sign=%@",[encodedValue stringByReplacingOccurrencesOfString:@" " withString:@""],fromString,toString,[NSString md5:signTo]];
    
    [[SeverceHttpRequest sharedManager] GET:urlString parameters:nil success:^(id reponseObject) {
        
        for (NSDictionary *dict in reponseObject[@"trans_result"]) {
            translationString = dict[@"dst"];
            originString = dict[@"src"];
            //添加数据
            [translationArray addObject:translationString];
            [originArray addObject:originString];
        }
        [self.cardView reloadData];
    } failure:^(NSError *error) {
        NSLog(@"网络请求失败");
    }];
}


- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    
    return [textField resignFirstResponder];
}


//通知方法
-(void)changeLanguage:(NSNotification *)not{
    [topView.fromBtn setTitle:not.object forState:UIControlStateNormal];
    languageStringFrom = not.object;
}

-(void)changeLanguageAgain:(NSNotification *)not{
    [topView.toBtn setTitle:not.object forState:UIControlStateNormal];
    languageStringTo = not.object;
}




//当键盘出现或改变时调用
-(void)keyboardWillShow:(NSNotification *)aNotification{
    //获取键盘高度
    NSDictionary *userinfo = [aNotification userInfo];
    NSValue *aValue = [userinfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    int height = keyboardRect.size.height;
    [UIView animateWithDuration:0.7 animations:^{
        bottomView.frame = CGRectMake(0, SCREEN_HEIGHT - height - 104, SCREEN_WIDTH, 40);
    }];
}


//当键盘退出时调用
-(void)keyboardWillHide:(NSNotification *)aNotification{
    
    [self netWorking];
    textFieldF.text = nil;
    [UIView animateWithDuration:0.7 animations:^{
        bottomView.frame = CGRectMake(0, SCREEN_HEIGHT - 104, SCREEN_WIDTH, 60);
    }];
}



-(void)clickBtn{
    NSLog(@"点击语音按钮");
}


-(void)setupTopView{
    topView = [[XYJLanguageTopView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 50)];
    [topView setupSubViewsFromText:languageStringFrom toText:languageStringTo];
    topView.delegate = self;
    [self.view addSubview:topView];
}

-(void)clickFrom:(id)sender{
    NSLog(@"点击自动检测");
    XYJLanguageFromViewController *VC = [[XYJLanguageFromViewController alloc] init];
    VC.languageCategory = languageStringFrom;
    [self.navigationController pushViewController:VC animated:YES];
    
}

-(void)clickTo:(id)sender{
    NSLog(@"点击转换成语言");
    XYJLanguageToViewController *VC = [[XYJLanguageToViewController alloc] init];
    VC.languageCategory = languageStringTo;
    [self.navigationController pushViewController:VC animated:YES];
}

-(void)clickChange:(id)sender{
    NSLog(@"点击交换");
}
     
@end
